/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.mongodb.domain.repository;

import java.io.Serializable;

import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.MongoRepositoryFactory;
import org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

/**
 * @description
 *
 * @author rening
 * @version v1.0
 *
 * @2013-6-24
 *
 */
public class EntityRepositoryFactoryBean<R extends MongoRepository<T, I>, T, I extends Serializable> extends
		MongoRepositoryFactoryBean<R, T, I> {

	/* (non-Javadoc)
	 * @see org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean#getFactoryInstance(org.springframework.data.mongodb.core.MongoOperations)
	 */
	@Override
	public RepositoryFactorySupport getFactoryInstance(MongoOperations operations) {
		return new EntityRepositoryFactory<T, Serializable>(operations);
	}

	private static class EntityRepositoryFactory<T, I extends Serializable> extends MongoRepositoryFactory {

		private MongoOperations mongoOperations;
		
		public EntityRepositoryFactory(MongoOperations mongoOperations) {
			super(mongoOperations);
			this.mongoOperations = mongoOperations;
		}

		@Override
	    protected Object getTargetRepository(RepositoryMetadata metadata) {
	    	MongoEntityInformation<?, Serializable> entityInformation = getEntityInformation(metadata.getDomainType());
	    	return new EntityRepositoryImpl(entityInformation, mongoOperations);
	    }

		@Override
	    protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
		      // The RepositoryMetadata can be safely ignored, it is used by the JpaRepositoryFactory
		      //to check for QueryDslJpaRepository's which is out of scope.
	    	return EntityRepository.class;
	    }
	}
}
